<template>
  <div>
    <InputWrap
      id="menu-activator"
      v-model="modelValue"
      :label="props.label"
      :placeholder="props.placeholder"
      :bg-dark="true"
      :append-icon="appendIcon"
      @input="onInput"
      @click="isActive = !isActive"
    ></InputWrap>
    <v-menu activator="#menu-activator" z-index="3000">
      <div class="pt-2 bg-surface elevation-10 menu">
        <v-virtual-scroll :items="searchItems" height="200">
          <template #default="{ item }">
            <div
              class="pa-1 item"
              :class="{ selected: item[`${props.itemTitle}`] === modelValue }"
              @click="clickItem(item[`${props.itemValue}`])"
            >
              <div>{{ item[`${props.itemTitle}`] }}</div>
            </div>
          </template>
        </v-virtual-scroll>
      </div>
    </v-menu>
  </div>
</template>
<script setup>
import { computed, nextTick, ref } from 'vue'
import { VMenu, VVirtualScroll } from 'vuetify/components'
import InputWrap from '@/components/form/InputWrap.vue'

nextTick()

const props = defineProps({
  modelValue: {
    required: true,
  },
  items: {
    type: Array,
    required: true,
  },
  itemTitle: {
    type: String,
    required: false,
    default: 'name',
  },
  itemValue: {
    type: String,
    required: false,
    default: 'code',
  },
  placeholder: {
    type: String,
    required: true,
  },
  label: {
    type: String,
  },
  bgDark: {
    type: Boolean,
    default: false,
  },
  search: {
    type: Boolean,
    default: false,
  },
})
const emit = defineEmits(['update:modelValue', 'click:option'])
const modelValue = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})

const isActive = ref(false)
const appendIcon = computed(() => (isActive.value ? 'up' : 'down'))

const clickItem = (value) => {
  emit('click:option', value)
  const text = props.items.find((item) => item[`${props.itemValue}`] === value)[`${props.itemTitle}`]
  modelValue.value = text
  isActive.value = false
}

const searchItems = computed(() =>
  props.search && modelValue.value
    ? props.items.filter((item) => item[`${props.itemTitle}`].includes(modelValue.value))
    : props.items,
)

const onInput = () => (props.search && modelValue.value ? (isActive.value = true) : (isActive.value = false))
</script>
<style scoped lang="scss">
.menu {
  position: relative;
  width: 100%;
  border-radius: 0.625rem;
}
.item {
  color: #ffffff;

  font-size: 0.875rem;
  font-style: normal;
  font-weight: 400;
  line-height: 140%;
  letter-spacing: 0.0125rem;
}
.selected {
  background-color: #181925;
}
</style>
